﻿//-----------------------------------------------------------------------
// <copyright file="Trace.cs">
//     Copyright (c) Wolf166 - BGF Framework
// </copyright>
// <Autor>Wolf166 - BGF Framework</Autor>
//-----------------------------------------------------------------------
namespace BrowserGameFramework.Common.Logging
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Configuration;
    using BrowserGameFramework.Common.Exceptions;

    /// <summary>
    /// Traceclass
    /// </summary>
    public static class Trace
    {
        /// <summary>
        /// Threadsave lock
        /// </summary>
        private static object fileLock = new object();

        /// <summary>
        /// Traces an enter message intoe logfile
        /// </summary>
        /// <param name="method">Name of Method</param>
        public static void TraceEnterEvent(string method)
        {
            TraceMessage(String.Format("Entering location {0}", method), Enums.TraceLevel.Verbose);
        }

        /// <summary>
        /// Traces an leave message intoe logfile
        /// </summary>
        /// <param name="method">Name of Method</param>
        public static void TraceLeaveEvent(string method)
        {
            TraceMessage(String.Format("Leaving location {0}", method), Enums.TraceLevel.Verbose);
        }

        /// <summary>
        /// Traces an exception into the logfile
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ex"></param>
        public static void TraceExceptionError(string message, Exception ex)
        {
            TraceMessage(string.Format("Message '{0}' StackTrace'{1}' InnerException '{2}'", message, ex.StackTrace,ex.InnerException != null ? ex.InnerException.Message :string.Empty), Enums.TraceLevel.Error);
        }

        /// <summary>
        /// Traces an error into the logfile
        /// </summary>
        /// <param name="message"></param>
        public static void TraceError(string message)
        {
            TraceMessage(message, Enums.TraceLevel.Error);
        }

        /// <summary>
        /// Traces the message into the logfile.
        /// </summary>
        /// <param name="Message">The message.</param>
        /// <param name="traceLevel">Set the tracelevel. Configure the Loglevel on Application Config file</param>
        /// <remarks>This methods log threadsave into a logfile on harddisk</remarks>
        public static void TraceMessage(string Message, Enums.TraceLevel traceLevel)
        {
            lock (fileLock)
            {
                try
                {
                    // Don't log, if the tracelevel is lower then the configured value
                    if (DoLog(traceLevel))
                    {
                        FileStream file = new FileStream(GetLogFilePath(), FileMode.Append, FileAccess.Write, FileShare.Write);
                        StreamWriter writer = new StreamWriter(file);
                        string def = traceLevel.ToString() + " " + DateTime.Now.ToShortTimeString() + " ";
                        writer.Write(def + Message + System.Environment.NewLine);
                        writer.Flush();
                        file.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw new BGFLoggingException("Error while logging", ex);
                }
            }
        }

        /// <summary>
        /// Gets teh LogFilePath
        /// </summary>
        /// <returns>String with logfile path</returns>
        private static string GetLogFilePath()
        {
            DateTime dt = DateTime.Now;

            string date = dt.ToString("yyyy-M-dd");
            string path = ConfigurationManager.AppSettings["LogfileFolder"];

            if (string.IsNullOrEmpty(path))
            {
                throw new BGFLoggingException("Can't find Key 'LogfileFolder' on Application Config File.Please create the config tag");
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            return Path.Combine(path, date + ".log");
        }

        /// <summary>
        /// Decide to log with the configured loglevel
        /// </summary>
        /// <param name="traceLevel">The trace level.</param>
        /// <returns>True or False</returns>
        private static bool DoLog(Enums.TraceLevel traceLevel)
        {
            string path = ConfigurationManager.AppSettings["LogFileMode"];

            if (string.IsNullOrEmpty(path))
            {
                throw new BGFLoggingException("Can't find Key 'LogFileMode' on Application Config File.Please create the key");
            }

            int key = 0;
            int value = 0;
            bool result = Int32.TryParse(path, out key);

            if (!result)
            {
                throw new BGFLoggingException("Error while parsing loglevel key.Check configuration file!");
            }

            switch (traceLevel)
            {
                case Enums.TraceLevel.Undefined: value = 0;
                    break;
                case Enums.TraceLevel.Error: value = 1;
                    break;
                case Enums.TraceLevel.Warning: value = 2;
                    break;
                case Enums.TraceLevel.Information: value = 3;
                    break;
                case Enums.TraceLevel.Verbose: value = 4;
                    break;
            }

            // if current logvalue is greater then the configured key, log into the Logfile.
            if (value <= key)
            {
                return true;
            }

            return false;
        }
    }
}
